package com.mdd.admin.service.teacher.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.teacher.ITeacherService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.teacher.TeacherParam;
import com.mdd.admin.vo.teacher.TeacherListVo;
import com.mdd.admin.vo.teacher.TeacherDetailVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.course.Course;
import com.mdd.common.entity.course.CourseCategory;
import com.mdd.common.entity.teacher.Teacher;
import com.mdd.common.mapper.course.CourseMapper;
import com.mdd.common.mapper.teacher.TeacherMapper;
import com.mdd.common.utils.ArrayUtil;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.ToolsUtil;
import com.mdd.common.utils.UrlUtil;
import com.mdd.common.config.GlobalConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 讲师实现类
 * @author panweiliang
 */
@Service
public class TeacherServiceImpl implements ITeacherService {
        
    @Resource
    TeacherMapper teacherMapper;

    @Resource
    CourseMapper courseMapper;

    /**
     * 讲师列表
     *
     * @author panweiliang
     * @param pageParam 分页参数
     * @param params 搜索参数
     * @return PageResult<TeacherListVo>
     */
    @Override
    public PageResult<TeacherListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        MPJQueryWrapper<Teacher> mpjQueryWrapper = new MPJQueryWrapper<Teacher>()
                .selectAll(Teacher.class)
                .select("SUM(CASE WHEN course.category_id IS NOT NULL THEN 1 ELSE 0 END) as courseCount, SUM(IFNULL(course.study_num, 0)) as totalStudyNum, SUM(IFNULL(course.virtual_study_num, 0)) as totalVirtualStudyNum ")
                .leftJoin("?_course course ON course.teacher_id=t.id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                .groupBy("t.id")
                .orderByDesc(Arrays.asList("t.sort", "t.id"));

        teacherMapper.setSearch(mpjQueryWrapper, params, new String[]{
                "like:name@t.name:str",
                "=:status@t.status:int",
        });

        IPage<TeacherListVo> iPage = teacherMapper.selectJoinPage(new Page<>(page, limit), TeacherListVo.class, mpjQueryWrapper);

        for(TeacherListVo item : iPage.getRecords()) {
            item.setAvatar(UrlUtil.toAbsoluteUrl(item.getAvatar()));
            item.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            item.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }

    /**
     * 讲师列表
     *
     * @author panweiliang
     * @return List<TeacherListVo>
     */
    @Override
    public List<TeacherDetailVo> getAll() {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<Teacher>()
                .eq("status", "1");
        List<Teacher> list = teacherMapper.selectList(queryWrapper);
        List<TeacherDetailVo> resultList = new LinkedList<>();
        for(Teacher item : list) {
            TeacherDetailVo vo = new TeacherDetailVo();
            BeanUtils.copyProperties(item, vo);
            vo.setAvatar(UrlUtil.toAbsoluteUrl(item.getAvatar()));
            resultList.add(vo);
        }
        return resultList;
    }


    /**
     * 讲师详情
     *
     * @author panweiliang
     * @param id 主键参数
     * @return Teacher
     */
    @Override
    public TeacherDetailVo detail(Integer id) {
        Teacher model = teacherMapper.selectOne(
                new QueryWrapper<Teacher>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        TeacherDetailVo vo = new TeacherDetailVo();
        BeanUtils.copyProperties(model, vo);
        vo.setAvatar(UrlUtil.toAbsoluteUrl(model.getAvatar()));
        return vo;
    }

    /**
     * 讲师新增
     *
     * @author panweiliang
     * @param teacherParam 参数
     */
    @Override
    public void add(TeacherParam teacherParam) {
        Teacher model = new Teacher();
        model.setNumber(this.randMakeTeacherNumber());
        model.setName(teacherParam.getName());
        model.setAvatar(UrlUtil.toRelativeUrl(teacherParam.getAvatar()));
        model.setGender(teacherParam.getGender());
        model.setSynopsis(teacherParam.getSynopsis());
        model.setIntroduce(teacherParam.getIntroduce());
        model.setStatus(teacherParam.getStatus());
        model.setSort(teacherParam.getSort());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        teacherMapper.insert(model);
    }

    /**
     * 讲师编辑
     *
     * @author panweiliang
     * @param teacherParam 参数
     */
    @Override
    public void edit(TeacherParam teacherParam) {
        Teacher model = teacherMapper.selectOne(
                new QueryWrapper<Teacher>()
                    .eq("id",  teacherParam.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        model.setId(teacherParam.getId());
//        model.setNumber(teacherParam.getNumber());
        model.setName(teacherParam.getName());
        model.setAvatar(UrlUtil.toRelativeUrl(teacherParam.getAvatar()));
        model.setGender(teacherParam.getGender());
        model.setSynopsis(teacherParam.getSynopsis());
        model.setIntroduce(teacherParam.getIntroduce());
        model.setStatus(teacherParam.getStatus());
        model.setSort(teacherParam.getSort());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        teacherMapper.updateById(model);
    }

    /**
     * 讲师删除
     *
     * @author panweiliang
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        Teacher model = teacherMapper.selectOne(
                new QueryWrapper<Teacher>()
                    .eq("id", id)
                    .last("limit 1"));
        Assert.notNull(model, "讲师不存在!");


        QueryWrapper<Course> queryWrapper = new QueryWrapper<Course>()
                .eq("teacher_id", id);

        Integer count = this.courseMapper.selectCount(queryWrapper);

        Assert.isTrue(count.intValue() == 0, "讲师已经关联了课程");

        teacherMapper.delete(new QueryWrapper<Teacher>().eq("id", id));
    }

    @Override
    public Teacher changeStatus(Integer id) {
        Teacher teacher = teacherMapper.selectOne(
                new QueryWrapper<Teacher>()
                        .eq("id", id)
                        .last("limit 1"));
        Assert.notNull(teacher, "讲师不存在!");
        teacher.setStatus(teacher.getStatus() == 1 ? 0 : 1);
        teacher.setUpdateTime(TimeUtil.timestamp());
        teacherMapper.updateById(teacher);
        teacher.setAvatar(UrlUtil.toAbsoluteUrl(teacher.getAvatar()));
        return teacher;
    }

    /**
     * 生成教师唯一编号
     *
     * @author panweiliang
     * @return Integer
     */
    private Long randMakeTeacherNumber() {
        Long number;
        while (true) {
            number = Long.parseLong(ToolsUtil.randomInt(8));
            Teacher snModel = teacherMapper.selectOne(new QueryWrapper<Teacher>()
                    .select("id, number, name")
                    .eq("number", number)
                    .last("limit 1"));
            if (snModel == null) {
                break;
            }
        }
        return number;
    }

}
